#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>

#define FORMAT "[%s@%s %s]# "
#define COMMAND_SIZE 1024

// 命令行参数表
#define MAX_ARGC 128
int g_argc=0;
char *g_argv[MAX_ARGC];

char cwd[1024];
char cwdenv[2048];

#define MAX_ENVS 100
int g_envs=0;
char* g_env[MAX_ENVS];

int lastcode = 0;

const char *GetUserName()
{
    const char *username = getenv("USER");
    return username == NULL ? "NONE" : username;
}

const char *GetHostName()
{
    const char *hostname = getenv("HOSTNAME");
    return hostname == NULL ? "NONE" : hostname;
}

const char *GetHome()
{
    const char *home = getenv("HOME");
    return home == NULL ? "" : home;
}

const char *GetPwd()
{
    const char *pwd = getcwd(cwd, sizeof(cwd));

    if (pwd != NULL)
    {
        snprintf(cwdenv, sizeof(cwdenv), "PWD=%s", cwd);
        putenv(cwdenv);
    }

    return pwd == NULL ? "NONE" : pwd;
}

std::string GetDirName(const char *pwd)
{
#define SLASH "/"

    std::string dir = pwd;

    if (dir == SLASH)
    {
        return "/";
    }

    auto pos = dir.rfind(SLASH);

    if (pos == std::string::npos)
    {
        return "BUG?";
    }

    return dir.substr(pos + 1);
}

void InitEnv()
{
    extern char** environ;

    memset(g_env,0,sizeof(g_env));
    g_envs=0;

    //导入父进程的环境变量，本应该从配置文件中来
    for(int i=0;environ[i];i++)
    {
        g_env[i]=(char*)malloc(strlen(environ[i])+1);
        strcpy(g_env[i],environ[i]);
        g_envs++;
    }

    g_env[g_envs++]=(char*)"HAHA=for test";
    g_env[g_envs++]=NULL;

    //导入自己的环境变量表
    for(int i=0;g_env[i];i++)
    {
        putenv(g_env[i]);
    }
}

bool Cd()
{
    if (g_argc == 1)
    {
        std::string home = GetHome();
        if (home.empty())
        {
            return false;
        }

        chdir(home.c_str());
    }
    else
    {
        std::string where = g_argv[1];
        std::string home = GetHome();
        if (where == "-")
        {
            // TODO
        }
        else if (where == "~")
        {
            chdir(home.c_str());
        }
        else
        {
            chdir(where.c_str());
        }
    }

    return true;
}

void Echo()
{
    if(g_argc==2)
    {
        std::string opt=g_argv[1];

        if(opt=="$?")
        {
            std::cout<<lastcode<<std::endl;
            lastcode=0;
        }
        else if(opt[0]=='$')
        {
            std::string env_name=opt.substr(1);
            //获取环境变量的值
            const char* env_value=getenv(env_name.c_str());
            if(env_value)
            {
                std::cout<<env_value<<std::endl;
            }  
        }
        else 
        {
            std::cout<<opt<<std::endl;
        }
    }
}

void Export()
{
    if(g_argc==2)
    {
        putenv(g_argv[1]);
        lastcode=0;
    }
    else 
    {
        lastcode=1;
    }
}

void MakeCommandLine(char prompt[], size_t size)
{
    snprintf(prompt, size, FORMAT, GetUserName(), GetHostName(), GetDirName(GetPwd()).c_str());
}

void PrintCommandPrompt()
{
    char prompt[COMMAND_SIZE];
    MakeCommandLine(prompt, sizeof(prompt));
    printf("%s", prompt);
    fflush(stdout);
}

bool GetCommandLine(char *out, size_t size)
{
    char *c = fgets(out, size, stdin);
    if (c == NULL)
    {
        return false;
    }

    out[strlen(out) - 1] = 0;
    if (strlen(out) == 0)
    {
        return false;
    }

    return true;
}

bool CommandParse(char *cmd)
{
#define SEP " "

    g_argc = 0;

    g_argv[g_argc++] = strtok(cmd, SEP);

    while ((bool)(g_argv[g_argc++] = strtok(nullptr, SEP)))
        ;

    g_argc--;

    return g_argc > 0 ? true : false;
}

bool CheakAndExecBuiltin()
{
    std::string cmd = g_argv[0];

    if (cmd == "cd")
    {
        Cd();
        return true;
    }
    else if (cmd == "echo")
    {
        Echo();
        return true;
    }
    else if (cmd == "export")
    {
        Export();
        return true;
    }

    return false;
}

int Execute()
{
    pid_t id = fork();
    if (id == 0)
    {
        execvp(g_argv[0], g_argv);
        exit(1);
    }

    int status = 0;
    pid_t wpid = waitpid(id, &status, 0);
    if (wpid > 0)
    {
        lastcode = WEXITSTATUS(status);
    }

    return 0;
}

int main()
{

    InitEnv();

    while (1)
    {
        //1.输出命令提示符
        PrintCommandPrompt();

        char command[COMMAND_SIZE];

        //2.获取命令行输入
        if (!GetCommandLine(command, sizeof(command)))
        {
            continue;
        }

        //3.拆分解析命令行
        if (!CommandParse(command))
        {
            continue;
        }

        //4.处理内建命令
        if (CheakAndExecBuiltin())
        {
            continue;
        }

        //5.执行命令
        Execute();
    }

    return 0;
}